const App = getApp();
// 工具类
import Util from '../../../../utils/util.js';
Page({
  data: {
    isLogin: false,
    teamId:0,
    article_id:0,
    detail:{article_status:1},
    maoHao: '：',
    fileList: [],
    categoryList:[],
    cateindex:0,//下标
    cate_name:'',//分类选中回显
    cate_id:0,//选中的分类ID
    location:1, //权限：1代表处，2分队
    isLocation:false, //是否选择权限
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      article_id:options.nid,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    that.setData({
      isLogin: App.checkIsLogin(),
    });
    if (that.data.isLogin) {
      //10007分队管理，10008代表处管理，10009分队管理+代表处管理
      let user_info = wx.getStorageSync('user_info') //用户信息
      //获取服务队
      that.setData({
        teamId: App.checkTeam(),
        isLocation:user_info.grade_id == "10009"?true:false
      });
      if(that.data.article_id > 0){
        // 资讯详情
        that.getDetail();
      }
      // 分类
      that.getCate();
    }
  },
  // 分类
  getCate(){
    let that = this;
    App._get('article', {}, result => {
      that.setData({
        categoryList: result.data.categoryList
      }); 
    });
  },
  /**
   * 资讯详情
   */
  getDetail() {
    let _this = this;
    let obj = {
      article_id:this.data.article_id
    }
    App._get('article/detail', obj, result => {
      const fileList = [];
      // // 将图片信息添加到fileList数字中
      fileList.push({
        file_id:result.data.detail.image.file_id,
        url:result.data.detail.image.file_path
      });
      let location = 2; //默认分队
      if(result.data.detail.team_id == 0){ //代表处
        location = 1;
      }
      _this.setData({
        detail: result.data.detail,
        cate_id:result.data.detail.category.category_id,
        cate_name:result.data.detail.category.name,
        fileList,
        location
      })
    });
  },

  // 删除照片
  deleteClick(event) {
    var imgData = this.data.fileList;
    // 通过splice方法删除图片
    imgData.splice(event.detail.index, 1);
    // 更新图片数组
    this.setData({
        fileList: imgData
    })
    console.log(this.data.fileList)
  },
  // 图片上传
  afterRead(event) {
    let that = this;
    // loading加载
    wx.showLoading({title: '上传中...'});
    //获取图片详细信息
    const {file} = event.detail;
    //调用上传图片方法
    that.uploadCompressImg(file).then(res=>{
      App.uploadFile(res,{},function(result){
        const fileList = [];
        // // 将图片信息添加到fileList数字中
        fileList.push({
            url: result.data.file_path,
            file_id:result.data.file_id,
        });
        // 更新存放图片的数组
        that.setData({
            fileList
        });
         wx.hideLoading();//停止loading
      })
    })

  },
  
  //提交
  formSubmit(e) {
    var formData=e.detail.value;//获取表单数据
    if(formData.article_title == ""){
      App.showError("标题不能空!");
      return;
    }
    if(!this.data.fileList.length){
      App.showError("封面图片不能空!");
      return;
    }
    if(formData.article_content == ""){
      App.showError("内容不能空!");
      return;
    }
    let obj = {
      article_id:this.data.article_id,
      article_title:formData.article_title, //标题
      article_content:formData.introduce, //内容
      image_id:this.data.fileList[0].file_id, //图片ID
      location:this.data.location,//1代表处，2分队
      category_id:this.data.cate_id==0?this.data.categoryList[this.data.cateindex].category_id:this.data.cate_id//分类id
    };
    console.log(obj);
    App._post_form('article/edit', obj, result => {
      //成功提示
      App.showSuccess(result.msg, function() {
        wx.navigateTo({
          url: "/pages/user/news/index",
        })
      });
    });
  },

  //发布位置
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      location:e.detail.value
    })
  },

  //选择分类
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      cateindex: e.detail.value,
      cate_id:this.data.categoryList[e.detail.value].category_id,
      cate_name:this.data.categoryList[e.detail.value].name,
    })
  },

  //图片压缩
  uploadCompressImg(file) {
    let that = this
    return new Promise(function(resolve, reject){
      let file_url = file.tempFilePath
      console.log(file);
      if(file.size < 500*1024){
        console.log("size",file.size)
        console.log("file_url",file_url)
        resolve(file_url);
      }else{
          // 获得原始图片大小
          wx.getImageInfo({
            src: file_url,
            success(res) {
              console.log(res);
            
              let originHeight = res.height;
              let originWidth = res.width;
              // 压缩比例
              // 最大尺寸限制
              let maxWidth = 1024,
                maxHeight = 1024;
              // 目标尺寸
              let targetWidth = originWidth,
                targetHeight = originHeight;
              // 等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              // 更新 canvas 大小
              that.setData({
                "cw": targetWidth,
                "ch": targetHeight
              });
              // 尝试压缩文件，创建 canvas
              let ctx = wx.createCanvasContext('canvas');
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              //通过得到图片旋转的角度来调整显示方向以正确显示图片，主要解决 ios 系统上的图片会有旋转的问题
              let orientation = res.orientation;
              if (orientation == 'right') { //exif的6
                that.setData({
                  "cw": targetHeight,
                  "ch": targetWidth
                });
                ctx.rotate(90 * Math.PI / 180);
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight, 0, -targetHeight, that.data.ch, that.data.cw);
              } else {
                ctx.drawImage(file_url, 0, 0, targetWidth, targetHeight);
              }

              ctx.draw(false, function () {
                // 获得新图片输出
                wx.canvasToTempFilePath({
                  x: 0,
                  y: 0,
                  canvasId: 'canvas',
                  destWidth: targetWidth,
                  destHeight: targetHeight,
                  quality: 0.9,
                  fileType: "jpg",
                  success: (res) => {
                    console.log(res)
                    resolve(res.tempFilePath);
                  },
                  fail: (err) => {
                    console.error(err)
                  }
                }, this)
              })
            }
          })
      }
    })
  },
})